package fm.dongman.modellib.source

import android.app.Activity
import android.content.Context
import fm.dongman.animefm.contractlib.BaseDataSource
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.SettingContract
import fm.dongman.modellib.RemoteHelper
import fm.dongman.modellib.StaticArea.StaticUrl
import fm.dongman.modellib.integrated.QQWBWXLoginHelper
import fm.dongman.modellib.local.DataOperationHelper
import fm.dongman.modellib.model.FeedBackModel

/**
 * 设置数据操作
 * Created by shize on 2017/11/19.
 */
class SettingRepository constructor(private var context: Context) : SettingContract.ISettingDataSource {

    override fun getData(callback: BaseDataSource.LoadSourceCallback<String>) {
        val json = RemoteHelper.instance.parsePostUrl("http://api.dongman.fm/about/checkUpdate", mapOf(Pair("current_version",getVersionName(context))))
        if (json == null)
        {
            callback.onDataLoadFiled()
        }else if (!json.getJSONObject(":data").getBoolean("is_latest_version"))
        {
            callback.onDataLoaded(json.getJSONObject(":data").getString("latest_download_url"))
        }else callback.onDataLoadFiled()
    }

    /**
     * 获取版本号
     */
    private fun getVersionName(context: Context): String {
        return context.packageManager.getPackageInfo(context.packageName, 0).versionName
    }

    override fun getAbout(): String {
        return URL_ABOUT
    }

    override fun sendFeedBack(feedback: IModel.IFeedBackModel, callback: BaseDataSource.LoadSourceCallback<String>) {
        val model:FeedBackModel = feedback as FeedBackModel
        val json = RemoteHelper.instance.parsePostUrl(" http://api.dongman.fm/about/submitFeedback", mapOf(Pair("x-token",StaticUrl.TOKEN_KEY)), mapOf( Pair("content",model.content), Pair("type",model.type)))
        if (json == null)
        {
            callback.onDataLoadFiled()
        }else callback.onDataLoaded("")
    }

    override fun logout(callback: BaseDataSource.LoadSourceCallback<String>) {
        DataOperationHelper.getInstance().deleteUser()
        QQWBWXLoginHelper.doQQLogout(context as Activity)
        callback.onDataLoaded("登出成功！")
    }

    override fun cleanCache(callback: BaseDataSource.LoadSourceCallback<String>) {
        callback.onDataLoaded("")
    }

    override fun refreshData() {}

    override fun offLine() {}

    override fun saveData(dataModel: String) {}

    companion object {
        val URL_ABOUT = "file:///android_asset/about.html" // 关于的地址

        fun getInstance(context: Context): SettingRepository {
            return SettingRepository(context)
        }
    }
}